#include"AddressWidget.h"
#include"NewAddressTab.h"
#include<QMessageBox>
#include"AddDialog.h"
#include<QLineEdit>
#include<QTextEdit>
#include<QTableView>
#include<QSortFilterProxyModel>
#include<QHeaderView>
#include"Contact.h"


AddressWidget::AddressWidget(QWidget* parent )
    :QTabWidget(parent)
{
	table_ = new TableModel(this);
    newAddressTab_ = new NewAddressTab(this);
    connect(newAddressTab_ , &NewAddressTab::sendDetails, this , &AddressWidget::addEntry);

    addTab(newAddressTab_ , tr("Address Book"));

	setupTabs();
}

void AddressWidget::readFromFile(const QString& fileName)
{
	QFile file(fileName);

	if(!file.open(QIODevice::ReadOnly))
	{
		QMessageBox::information(this , tr("Unable to open file") ,
				file.errorString());
		return;
	}

	QList<Contact> contacts;
	QDataStream in(&file);
	in >> contacts;

	if(contacts.isEmpty())
	{
		QMessageBox::information(this ,tr("No contacts in file"),
				tr("The file you are attempting to open contains no contacts."));
	}else{
		for(const auto & contact :  qAsConst(contacts))
		{
			addEntry( contact.name_ , contact.address_);
		}
	}
}

void AddressWidget::writeToFile(const QString& fileName)
{
	QFile  file(fileName);

	if(!file.open(QIODevice::WriteOnly))
	{
        QMessageBox::information(this , "Unable to open file" , file.errorString());
		return ;
	}

	QDataStream out(&file);
	out << table_->getContacts();
}


void AddressWidget::showAddEntryDialog()
{
	AddDialog dlg;
	if(dlg.exec())
	{
        QString name = dlg.nameText_->text();
        QString address = dlg.addressText_->toPlainText();

		addEntry(name , address);
	}
}

void AddressWidget::addEntry(const QString & name , const QString& address)
{
	if(!table_->getContacts().contains({name ,address}))
	{
		table_->insertRows(0 , 1 , QModelIndex());

		QModelIndex index = table_->index(0 , 0 , QModelIndex());
		table_->setData(index , name , Qt::EditRole);

		index = table_->index(0,1,QModelIndex());
		table_->setData(index , address , Qt::EditRole);

		removeTab(indexOf(newAddressTab_));
	}else{
		QMessageBox::information(this ,  tr("Duplicate Name"),
				tr("The name \"%1\" already exists.").arg(name));
	}
}

void AddressWidget::editEntry()
{
	QTableView* temp = static_cast<QTableView*>(currentWidget());
	QSortFilterProxyModel* proxy = static_cast<QSortFilterProxyModel*>(temp->model());
	QItemSelectionModel* selectionModel = temp->selectionModel();

	QModelIndexList indexes = selectionModel->selectedRows();
	QString name;
	QString address;
	int row = -1;

	foreach(QModelIndex index , indexes)
	{
		row = proxy->mapToSource(index).row();
		QModelIndex nameIndex = table_->index( row , 0 , QModelIndex());
		QVariant varName =table_->data(nameIndex , Qt::DisplayRole);
		name = varName.toString();

		QModelIndex addressIndex = table_->index(row ,1 ,QModelIndex());
		QVariant varAddr = table_->data(addressIndex , Qt::DisplayRole);
		address = varAddr.toString();
	}

	AddDialog  dlg;
	dlg.setWindowTitle(tr("Edit a Contact"));

    dlg.nameText_->setReadOnly(true);
    dlg.nameText_->setText(name);
    dlg.addressText_->setText(address);

	if(dlg.exec())
	{
        QString newAddress = dlg.addressText_->toPlainText();
        if(newAddress != address)
		{
			QModelIndex index =  table_->index(row , 1 , QModelIndex());
			table_->setData(index , newAddress , Qt::EditRole);
		}
	}
}

void AddressWidget::removeEntry()
{
	QTableView* temp = static_cast<QTableView*>(currentWidget());
	QSortFilterProxyModel* proxy = static_cast<QSortFilterProxyModel*>(temp->model());
	QItemSelectionModel* selectionModel = temp->selectionModel();

	QModelIndexList indexes = selectionModel->selectedRows();

    foreach(QModelIndex index ,indexes)
	{
		int row = proxy->mapToSource(index).row();
		table_->removeRows(row , 1 , QModelIndex());
	}

	if(table_->rowCount(QModelIndex()) == 0)
	{
		insertTab(0 , newAddressTab_ , tr("Address Book"));
	}
}


void AddressWidget::setupTabs()
{
	QStringList groups;
	groups <<tr("ABC")<<tr("DEF")<<tr("GHI")<<tr("JKL")<<tr("MNO")<<tr("PQR")<<tr("STU")<<tr("VW")<<tr("XYZ");

	for(int i=0; i<groups.size(); ++i)
	{
		QString str = groups.at(i);
        QString regExp = QString(tr("^[%1].*").arg(str));

		proxyModel_ = new QSortFilterProxyModel(this);
		proxyModel_->setSourceModel(table_);
		proxyModel_->setFilterRegExp(QRegExp(regExp , Qt::CaseInsensitive));
        proxyModel_->setFilterKeyColumn(0);

		QTableView* tableView = new QTableView;
		tableView->setModel(proxyModel_);

		tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
		tableView->horizontalHeader()->setStretchLastSection(true);
		tableView->verticalHeader()->hide();
		tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
		tableView->setSelectionMode(QAbstractItemView::SingleSelection);

		tableView->setSortingEnabled(true);

		connect(tableView->selectionModel(),
			&QItemSelectionModel::selectionChanged,
			this , &AddressWidget::selectionChanged);

		connect(this , &QTabWidget::currentChanged , this , [this](int tabIndex){
				auto* tableView = qobject_cast<QTableView*>(widget(tabIndex));

				if(tableView)
				{
					emit selectionChanged(tableView->selectionModel()->selection());
				}
				});

		addTab(tableView , str);
	}
}


